$(document).ready(function () {
  let $newsList = $('.news-list');   //对应newsList容器
  let $tagList = $('.news-nav li');    //对应每一个tag标签
  let $more = $('.btn-more');
  let iPage = 1;        //设置默认的页数
  let iTgaId = 0;       //设置默认的tagId
  let currentTagId = iTgaId;   //当前的tag_id

  fn_load_page(iTgaId, iPage);
  $tagList.click(function () {
    //点击标签后，对当前页的TagId重新赋值
    iTgaId = $(this).children('a').data('id');

    //判断当前点击的标签是不是页面加载的标签
    if (iTgaId !== currentTagId) {
      //清空news_list
      $newsList.children('li').slideUp(800);
      fn_load_page(iTgaId, iPage = 1);
      //参数iPage=1是为了点击标签后，令其重新从开头开始加载
      currentTagId = $(this).children('a').data('id');
    }
  });

  $more.click(function () {
    iPage += 1;
    fn_load_page(iTgaId, iPage)
  });

  //定义根据tag_id和iPage获取article的函数
  function fn_load_page(tag_id, page) {
    $.get({
      url: `/news/article/?tag_id=${tag_id}&&page=${page}`,
      dataType: 'json'
    })
        .done(function (res) {
          if (res.no === "0") {             //后端发来的响应json数据
            let data = res.data;            //将返回的数据转化成一个列表
            // console.log(data);
            //将列表中的每一项进行遍历并渲染到模板
            let article_arr = data.map(item => `
            <li class="news-item">
                   <a href="/news/details/${item.id}" class="news-thumbnail"
                                   target="_blank">
                         <img src="${item.thumbnail}" alt="${item.title}"
                                         title="${item.title}">
                    </a>
                    <div class="news-content">
                          <h4 class="news-title">
                          <a href="/news/details/${item.id}" target="_blank">${item.title}</a>
                           </h4>
                           <p class="news-details">${item.digest}
                           </p>
                           <div class="news-other">
                             <span class="news-type">${item.tag.name}</span>
                             <span class="news-time">${dateFormat(item.create_time)}</span>
                             <span class="news-author">${item.author.username}</span>
                           </div>
                     </div>
            </li>
            `);
            $newsList.append(article_arr.join(""))
          } else {
            message.showError(res.msg)
          }
        })
        //加载未完成时
        .fail(function () {
          message.showError("文章加载失败");
          $newsList.html("");
          $newsList.append("<h3 style='color: red;height:30px'>文章加载失败</h3>")
        })
  }

});